using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace GoodStuff
{
    public class MonochromeBitmapFunctions
    {

        public static Bitmap NewBitmapFromRectangle(Bitmap inputBitmap, Rectangle srcRect)
        {
            Bitmap b = new Bitmap(srcRect.Width, srcRect.Height, PixelFormat.Format8bppIndexed);
            SetMonochromePalette(b);
            BitmapData inputData = inputBitmap.LockBits(
                srcRect, 
                ImageLockMode.ReadOnly, 
                PixelFormat.Format8bppIndexed);
            BitmapData outputData = b.LockBits(
                new Rectangle(0,0,srcRect.Width, srcRect.Height),
                ImageLockMode.ReadWrite, 
                PixelFormat.Format8bppIndexed);
            unsafe
            {
                Byte* i = (Byte*)inputData.Scan0;
                Byte* o = (Byte*)outputData.Scan0;
                Byte* lastOutputPixel = o + srcRect.Width * srcRect.Height;
                Byte* endOfInputLine = i + srcRect.Width;

                while (o < lastOutputPixel)
                {
                    *o++ = *i++;
                    if (i == endOfInputLine)
                    {
                        i += inputBitmap.Width - srcRect.Width;
                        endOfInputLine += inputBitmap.Width;
                    }
                }
            }
            inputBitmap.UnlockBits(inputData);
            b.UnlockBits(outputData);
            return b;
        }


        public static void SetMonochromePalette(Bitmap b)
        {
            ColorPalette cp = b.Palette;
            for (int i = 0; i < 255; ++i)
                cp.Entries[i] = Color.FromArgb(i, i, i);
            b.Palette = cp;
        }
    }
}
